//
//  RoomMateTeamViewController.m
//  Fangmm
//
//  Created by ChaoZhou on 16/3/11.
//  Copyright © 2016年 com.fangmm. All rights reserved.
//

#import "RoomMateTeamViewController.h"
#import "RoomMateTeamTableViewCell.h"
#import "HttpServer.h"
#import "Utility.h"
#import "Constants.h"
#import <MJRefresh.h>
#import "Team.h"
#import <UIImageView+WebCache.h>
#import "Utility.h"
#import "Community.h"
#import "Seat.h"
#import "RoomMateListViewController.h"
#import "RoomMateApplyViewController.h"
#import "TwoButtonsPopViewController.h"
#import "WXApi.h"
#import <TSMessages/TSMessageView.h>
#import "HistoryTeamViewController.h"
#import "HouseDetailViewController.h"
#import "RoommateApplyStateViewController.h"
@interface RoomMateTeamViewController ()<UITableViewDataSource,UITableViewDelegate,RoomMateTeamTableViewCellDelegate,TwoButtonsViewDelegate,UIPopoverPresentationControllerDelegate>
{
    NSMutableArray      *teamArray;
    NSString            *userId;
    UIImageView         *defaultImage;
    UILabel             *label1;
    UILabel             *label2;
    UILabel             *label3;
    NSString            *shareUrl;
    WXMediaMessage      *shareMessage;
}
@end
@implementation RoomMateTeamViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"室友小组";
    self.view.backgroundColor = [UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1];
    UIBarButtonItem *leftBar = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"back-18-36"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(goToMain)];
    self.navigationItem.leftBarButtonItem = leftBar;
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"groupz"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(rightItemClick)];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tableDidSelected:) name:@"click" object:nil];
    self.navigationItem.rightBarButtonItem = rightBar;
    [rightBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:255.0/255 green:118/255.0 blue:108.0/255 alpha:1],NSFontAttributeName:[UIFont systemFontOfSize:12]} forState:UIControlStateNormal];
    userId = [Utility getObjectForKey:kUserId];
    teamArray = [NSMutableArray array];
    self.mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(pullToRefresh)];
    [self.mainTableView.mj_header beginRefreshing];
    _mainTableView.tableFooterView = [UIView new];
    [_mainTableView registerNib:[UINib nibWithNibName:@"RoomMateTeamTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"roomMateTeamTableViewCell"];
    _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

-(void)viewWillAppear:(BOOL)animated
{
    [self.itemPopVC dismissViewControllerAnimated:YES completion:nil];
    self.itemPopVC = nil;
    [self.mainTableView.mj_header beginRefreshing];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSLog(@"tableview-==%lu",(unsigned long)teamArray.count);
    return teamArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 197;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RoomMateTeamTableViewCell *roomTeamCell = [tableView dequeueReusableCellWithIdentifier:@"roomMateTeamTableViewCell"];
    roomTeamCell.delegate = self;
    Team *team = teamArray[indexPath.section];
    roomTeamCell.teamId = team.teamId;
    roomTeamCell.payButtonView.tag = indexPath.section;
    roomTeamCell.roomMateButton.tag = indexPath.section;
    [roomTeamCell.houseImage sd_setImageWithURL:[NSURL URLWithString:team.houseCover] placeholderImage:[UIImage imageNamed:@"Non_HP"]];
    
    
//    roomTeamCell.inviteButton.layer.masksToBounds = YES;
//    CAShapeLayer *maskLayer = [CAShapeLayer layer];
//    UIBezierPath *maskPath = ([UIBezierPath bezierPathWithRoundedRect:roomTeamCell.inviteButton.bounds byRoundingCorners: UIRectCornerBottomLeft | UIRectCornerTopLeft cornerRadii: CGSizeMake(5,5)]);
//    maskLayer.bounds = roomTeamCell.inviteButton.layer.bounds;
//    maskLayer.path = maskPath.CGPath;
//    roomTeamCell.inviteButton.layer.mask = maskLayer;
    
    
    
    if ([team.leaderId isEqualToString:[Utility getObjectForKey:kUserId]])
    {
        roomTeamCell.imageMask.text = @"室长";
        roomTeamCell.payButtonView.userInteractionEnabled = YES;
        if(team.applyNum == 0)
        {
            roomTeamCell.noteLabel.text = @"暂无新的室友申请";
        }
        if (team.applyNum > 0)
        {
           roomTeamCell.noteLabel.text = [NSString stringWithFormat:@"%d个新的室友",team.applyNum];
        }
    }
    else
    {
        roomTeamCell.payButtonView.userInteractionEnabled = NO;
        roomTeamCell.imageMask.text = @"室友";
    }
    roomTeamCell.createTimeLabel.text = [NSString stringWithFormat:@"%@成为%@",team.createTime,roomTeamCell.imageMask.text];
    roomTeamCell.houseName.text = team.houseCommunity;
    int SeatNum = 0;
    for (int i = 0; i < team.seatArray.count; i ++)
    {
        Seat *seat =  team.seatArray[i];
        if (seat.userId == nil || [seat.userId isEqualToString:@""])
        {
        }
        else
        {
            SeatNum ++;
        }
    }
    //满员判断
    if(SeatNum == team.seatArray.count)
    {
        roomTeamCell.joinedLabel.text = [NSString stringWithFormat:@"已有%lu名室友即可组团看房",(unsigned long)team.seatArray.count];
        roomTeamCell.inviteLabel.backgroundColor = [UIColor colorWithRed:253 green:168 blue:160 alpha:1];
        roomTeamCell.inviteButton.userInteractionEnabled = NO;
        roomTeamCell.noteTitleLabel.textColor = [UIColor colorWithRed:255.0/255 green:118.0/255 blue:108.0/255 alpha:1];
        roomTeamCell.noteTitleLabel.text = @"NEW";
    }
    else
    {
        roomTeamCell.joinedLabel.text = [NSString stringWithFormat:@"已有%d名室友,还需%lu名室友即可组团看房",SeatNum, team.seatArray.count - SeatNum];
        roomTeamCell.noteTitleLabel.textColor = [UIColor colorWithRed:160.0/255 green:160.0/255 blue:160.0/255 alpha:1];
        roomTeamCell.noteTitleLabel.text = @"NEW";
        roomTeamCell.noteImage.hidden = YES;
    }
    roomTeamCell.joinedNum.text = [NSString stringWithFormat:@"%d/%lu",SeatNum,(unsigned long)team.seatArray.count];
    switch (team.seatArray.count)
    {
        case 1:
        {
           roomTeamCell.roomAPriceLabel.text = (![team.leaderId isEqualToString:[Utility getObjectForKey:kUserId]] && ((Seat*)team.seatArray[0]).leader == YES) ? @"室长" : [NSString stringWithFormat:@"%d",((Seat*)team.seatArray[0]).rent];
            if ([((Seat*)team.seatArray[0]).userId isEqualToString:[Utility getObjectForKey:kUserId]])
            {
                roomTeamCell.roomAPriceLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
                roomTeamCell.roomAPriceLabel.textColor = [UIColor colorWithRed:255.0/255 green:118.0/255 blue:108.0/255 alpha:1];
                roomTeamCell.roomALabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
            }
            else
            {
                [UIColor colorWithRed:71.0/255 green:62.0/255 blue:58.0/255 alpha:1];
            }
            roomTeamCell.roomBLabel.hidden  = YES;
            roomTeamCell.roomBPriceLabel.hidden = YES;
            roomTeamCell.roomCLabel.hidden = YES;
            roomTeamCell.roomCPriceLabel.hidden = YES;
        }
            break;
        case 2:
        {
            roomTeamCell.roomAPriceLabel.text    = (![team.leaderId isEqualToString:[Utility getObjectForKey:kUserId]] && ((Seat*)team.seatArray[0]).leader == YES) ? @"室长" : [NSString stringWithFormat:@"%d",((Seat*)team.seatArray[0]).rent];
            roomTeamCell.roomBPriceLabel.text    = (![team.leaderId isEqualToString:[Utility getObjectForKey:kUserId]] && ((Seat*)team.seatArray[1]).leader == YES) ? @"室长" : [NSString stringWithFormat:@"%d",((Seat*)team.seatArray[1]).rent];
            if ([((Seat*)team.seatArray[0]).userId isEqualToString:[Utility getObjectForKey:kUserId]])
            {
                roomTeamCell.roomAPriceLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
                roomTeamCell.roomAPriceLabel.textColor = [UIColor colorWithRed:255.0/255 green:118.0/255 blue:108.0/255 alpha:1];
                roomTeamCell.roomALabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
            }
            else
            {
                [UIColor colorWithRed:71.0/255 green:62.0/255 blue:58.0/255 alpha:1];
            }
            
            if ([((Seat*)team.seatArray[1]).userId isEqualToString:[Utility getObjectForKey:kUserId]])
            {
                roomTeamCell.roomBPriceLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
                roomTeamCell.roomBPriceLabel.textColor = [UIColor colorWithRed:255.0/255 green:118.0/255 blue:108.0/255 alpha:1];
                roomTeamCell.roomBLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
            }
            else
            {
                [UIColor colorWithRed:71.0/255 green:62.0/255 blue:58.0/255 alpha:1];
            }
            roomTeamCell.roomCLabel.hidden = YES;
            roomTeamCell.roomCPriceLabel.hidden = YES;
        }
            break;
        default:
        {
            roomTeamCell.roomAPriceLabel.text    = (![team.leaderId isEqualToString:[Utility getObjectForKey:kUserId]] && ((Seat*)team.seatArray[0]).leader == YES) ? @"室长" : [NSString stringWithFormat:@"%d",((Seat*)team.seatArray[0]).rent];
            roomTeamCell.roomBPriceLabel.text    = (![team.leaderId isEqualToString:[Utility getObjectForKey:kUserId]] && ((Seat*)team.seatArray[1]).leader == YES) ? @"室长" : [NSString stringWithFormat:@"%d",((Seat*)team.seatArray[1]).rent];
            roomTeamCell.roomCPriceLabel.text    = (![team.leaderId isEqualToString:[Utility getObjectForKey:kUserId]] && ((Seat*)team.seatArray[2]).leader == YES) == YES ? @"室长" : [NSString stringWithFormat:@"%d",((Seat*)team.seatArray[2]).rent];
            if ([((Seat*)team.seatArray[0]).userId isEqualToString:[Utility getObjectForKey:kUserId]])
            {
                roomTeamCell.roomAPriceLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
                roomTeamCell.roomAPriceLabel.textColor = [UIColor colorWithRed:255.0/255 green:118.0/255 blue:108.0/255 alpha:1];
                roomTeamCell.roomALabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
            }
            else
            {
                [UIColor colorWithRed:71.0/255 green:62.0/255 blue:58.0/255 alpha:1];
            }
            NSLog(@"\n%@\n%@",((Seat*)team.seatArray[1]).userId,[Utility getObjectForKey:kUserId]);
            if ([((Seat*)team.seatArray[1]).userId isEqualToString:[Utility getObjectForKey:kUserId]])
            {
                roomTeamCell.roomBPriceLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
                roomTeamCell.roomBPriceLabel.textColor = [UIColor colorWithRed:255.0/255 green:118.0/255 blue:108.0/255 alpha:1];
                roomTeamCell.roomBLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
            }
            else
            {
                [UIColor colorWithRed:71.0/255 green:62.0/255 blue:58.0/255 alpha:1];
            }
            
            if ([((Seat*)team.seatArray[2]).userId isEqualToString:[Utility getObjectForKey:kUserId]])
            {
                roomTeamCell.roomCPriceLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
                roomTeamCell.roomCPriceLabel.textColor = [UIColor colorWithRed:255.0/255 green:118.0/255 blue:108.0/255 alpha:1];
                roomTeamCell.roomCLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
            }
            else
            {
                roomTeamCell.roomCPriceLabel.textColor = [UIColor colorWithRed:71.0/255 green:62.0/255 blue:58.0/255 alpha:1];
            }
            
        }
            break;
    }
    return roomTeamCell;
}
#pragma mark - cell'sDelegate
-(void)queryRoomMateWith:(UIButton *)sender
{
    NSLog(@"查询室友");
    RoomMateListViewController *roomMateListVC = [[RoomMateListViewController alloc]init];
    roomMateListVC.team = (Team*)(teamArray[sender.tag]);
    [self.navigationController pushViewController:roomMateListVC animated:YES];
}
#pragma mark - 处理室友申请页面
-(void)payDepositWith:(UIButton *)sender
{
    NSLog(@"处理室友申请页面");
    RoomMateApplyViewController *roomMateApplyVC = [[RoomMateApplyViewController alloc]init];
    roomMateApplyVC.teamId = ((Team*)(teamArray[sender.tag])).teamId;
    [self.navigationController pushViewController:roomMateApplyVC animated:YES];
}
-(void)inviteFriendWithTeamId:(NSString *)teamId
{
    NSLog(@"邀请好友fangfa");
    [self loadShareDatasWithTeamId:teamId];
    TwoButtonsPopViewController *twoButtonsVC = [[TwoButtonsPopViewController alloc]initWithNibName:@"TwoButtonsPopViewController" bundle:nil];
    [twoButtonsVC setDelegate:self];
    [self presentViewController:twoButtonsVC animated:true completion:^{
        twoButtonsVC.sourceView = @"Share";
        [twoButtonsVC.titleLabel setText:@"分享房源"];
        [twoButtonsVC.firstButton setBackgroundImage:[UIImage imageNamed:@"wechat"] forState:UIControlStateNormal];
        [twoButtonsVC.firstLabel setText:@""];
        [twoButtonsVC.secondButton setBackgroundImage:[UIImage imageNamed:@"fb"] forState:UIControlStateNormal];
        [twoButtonsVC.secondLabel setText:@""];
    }];
}
#pragma mark - Two buttons view delegate
- (void)sharebuttonClickedWithTag:(NSInteger)tag {
    SendMessageToWXReq *shareReq = [[SendMessageToWXReq alloc]init];
    shareReq.bText = false;
    shareReq.message = shareMessage;
    WXWebpageObject *webObj = [[WXWebpageObject alloc]init];
    webObj.webpageUrl = shareUrl;
    shareReq.message.mediaObject = webObj;

    switch (tag) {
        case 0:
        {
            shareReq.scene = 0;
            [WXApi sendReq:shareReq];
            [self dismissViewControllerAnimated:true completion:^{
            }];
        }
            break;
        default:
        {
            shareReq.scene = 1;
            [WXApi sendReq:shareReq];
            [self dismissViewControllerAnimated:true completion:^{
            }];
        }
            break;
    }
}

- (WXMediaMessage *)wechateShareData:(NSDictionary *)successDic {
    WXMediaMessage *message = [[WXMediaMessage alloc]init];
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:[successDic objectForKey:@"thumbnail"]] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
    } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
        message.thumbData = data;
    }];
    message.title = [successDic objectForKey:@"title"];
    message.description = [successDic objectForKey:@"description"];
    return message;
}

-(void)goToMain
{
    [self.itemPopVC dismissViewControllerAnimated:YES completion:nil];
    self.itemPopVC = nil;
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)pullToRefresh
{
    [HttpServer getRoomMateTeamWithUserId:userId withStatus:@"active" withPage:1 withPageSize:10 withUserInfo:nil withSuccessBlock:^(NSDictionary *reponseData)
     {
         NSLog(@"个人小组%@",reponseData);
         [teamArray removeAllObjects];

         for (NSDictionary *dic in reponseData[@"teams"])
         {
             Team *team = [[Team alloc]initWithDic:dic];
             [teamArray addObject:team];
         }
         [self.mainTableView.mj_header endRefreshing];
         [_mainTableView reloadData];
         if (teamArray.count == 0)
         {
             _mainTableView.hidden = YES;
             if(!defaultImage)
             {
                 defaultImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"OX_roomie182-110"]];
                 [defaultImage setFrame:CGRectMake(self.view.frame.size.width/2 - 45, self.view.frame.size.height/2 - 60, 91, 55)];
                 [self.view addSubview:defaultImage];
             }
             if (!label1)
             {
                 label1 = [[UILabel alloc]initWithFrame:CGRectMake(80, self.view.frame.size.height/2, self.view.frame.size.width - 160, 15)];
             }
             if (!label2)
             {
                 label2 = [[UILabel alloc]initWithFrame:CGRectMake(80, self.view.frame.size.height/2 + 20, self.view.frame.size.width - 160, 15)];
             }
             if (!label3)
             {
                 label3 = [[UILabel alloc]initWithFrame:CGRectMake(80, self.view.frame.size.height/2 + 40, self.view.frame.size.width - 160, 15)];
             }
             [self.view addSubview:label1];
             [self.view addSubview:label2];
             [self.view addSubview:label3];
             [label1 setTextAlignment:NSTextAlignmentCenter];
             [label2 setTextAlignment:NSTextAlignmentCenter];
             [label3 setTextAlignment:NSTextAlignmentCenter];
             label1.font = [UIFont systemFontOfSize:11];
             label2.font = [UIFont systemFontOfSize:11];
             label3.font = [UIFont systemFontOfSize:11];
             label1.textColor = [UIColor colorWithRed:71.0/255 green:62.0/255 blue:58.0/255 alpha:1];
             label2.textColor = [UIColor colorWithRed:71.0/255 green:62.0/255 blue:58.0/255 alpha:1];
             label3.textColor = [UIColor colorWithRed:71.0/255 green:62.0/255 blue:58.0/255 alpha:1];
             label1.text = @"当您成为室长或加入房源小组后";
             label2.text = @"小组信息会出现在这里";
             label3.text = @"快去寻找适合的房源加入吧！";
             defaultImage.hidden = NO ;
             label1.hidden = NO ;
             label2.hidden = NO ;
             label3 .hidden = NO;
         }
         if (teamArray.count > 0)
         {
             _mainTableView.hidden = NO;
             defaultImage.hidden = YES ;
             label1.hidden = YES ;
             label2.hidden = YES ;
             label3 .hidden = YES;
         }
     }
     withFailedBlock:^(id errorMsg)
     {
         NSLog(@"个人小组错误信息%@",errorMsg);
         [self.mainTableView.mj_header endRefreshing];
     }];
}

- (void)loadShareDatasWithTeamId:(NSString *)teamId
{
    if (teamId == nil || [teamId isEqual:@""])
    {
    }
    else
    {
        [HttpServer getSharelinksWithType:@"team" sharedInfo:teamId WithSuccessBlock:^(NSDictionary *successDic)
        {
            shareUrl = [successDic objectForKey:@"link"];
            shareMessage = [self wechateShareData:successDic];
        }
        withFailedBlock:^(id failData)
        {
            NSLog(@"%@",failData);
        }];
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HouseDetailViewController *houseDetailVC = [[HouseDetailViewController alloc]init];
    houseDetailVC.houseId = ((Team*)teamArray[indexPath.section]).houseId;
    [self.navigationController pushViewController:houseDetailVC animated:YES];
}
- (void)rightItemClick
{
    self.itemPopVC = [[PopoverViewController alloc] init];
    self.itemPopVC.modalPresentationStyle = UIModalPresentationPopover;
    self.itemPopVC.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItem;  //rect参数是以view的左上角为坐标原点（0，0）
    self.itemPopVC.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionUnknown; //箭头方向,如果是baritem不设置方向，会默认up，up的效果也是最理想的
    self.itemPopVC.popoverPresentationController.backgroundColor = [UIColor colorWithRed:71.0/255 green:62.0/255 blue:58.0/255 alpha:1];
    self.itemPopVC.popoverPresentationController.delegate = self;
    [self presentViewController:self.itemPopVC animated:YES completion:nil];
    
}
- (void)tableDidSelected:(NSNotification *)notification
{
    NSIndexPath *indexpath = (NSIndexPath *)notification.object;
    switch (indexpath.row)
    {
        case 0:
        {
            RoommateApplyStateViewController *roommateAppleVC = [[RoommateApplyStateViewController alloc]init];
            [self.navigationController pushViewController:roommateAppleVC animated:YES];
        }
        break;
        default:
        {
            HistoryTeamViewController *historyTeamVC =[[HistoryTeamViewController alloc]init];
            [self.navigationController pushViewController:historyTeamVC animated:YES];
        }
        break;
    }
    [self.itemPopVC dismissViewControllerAnimated:YES completion:nil];
    self.itemPopVC = nil;
}
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller
{
    return UIModalPresentationNone;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
